﻿using CommonLib;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppConsumer2;

internal class TestTopicPattern
{
    private static readonly string ExchangeName = "topic_logs";
    private static readonly string QueueName = "Q2";

    public static void TestTopic()
    {
        // 1 创建信道 channel
        var channel = RabbitMQUtil.CreateChannel();

        // 2 声明交换机
        channel.ExchangeDeclare(ExchangeName, "topic");

        // 3 创建Q1 队列
        channel.QueueDeclare(QueueName, false, false, false, null);

        // 4 绑定交换机
        channel.QueueBind(QueueName, ExchangeName, "*.*.rabbit");
        channel.QueueBind(QueueName, ExchangeName, "lazy.#");

        // 5 消费消息
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        async Task Consumer_Received(object sender, BasicDeliverEventArgs @event)
        {
            try
            {
                var body = @event.Body.ToArray();
                var msg = Encoding.UTF8.GetString(body);
                Console.WriteLine("Consumer2 收到了消息" + msg);
                channel.BasicAck(@event.DeliveryTag, false);
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                channel.BasicReject(@event.DeliveryTag, true);
                Console.WriteLine("处理消息：" + ex.Message);
            }
        }

        // 6 消费消息
        channel.BasicConsume(QueueName, false, consumer: consumer);
        Console.ReadLine();
    }


}
